package com.orangelife.webservice.service.feedetail.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import jxl.CellView;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.PropFeeType.IPropFeeTypeService;
import com.orangelife.service.cerHouseholder.ICerHouseholderService;
import com.orangelife.service.cerHouseholder.model.CerHouseholderDto;
import com.orangelife.service.feeDetail.IFeeDetailService;
import com.orangelife.service.feeDetail.impl.IImportFeeDetailHistory;
import com.orangelife.service.feeDetail.impl.ImportFeeDetailHistoryImpl;
import com.orangelife.service.feeDetail.modal.PropFeeDetailDto;
import com.orangelife.service.feelog.IFeeLogService;
import com.orangelife.service.feelog.modal.PropFeeLogDto;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeComm.model.PropFeeCommDto;
import com.orangelife.service.propFeeDetailImportLog.IPropFeeDetailImportLogService;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.feedetail.IFeeDetailWebService;
import com.orangelife.webservice.service.feedetail.entity.ChangeFeeTypeDto;

@Service("webservice_feeDetail")
public class FeeDetailWebServiceImpl extends BaseService implements
		IFeeDetailWebService {

	@Resource(name = "propFeeTypeService")
	private IPropFeeTypeService propFeeTypeService;
	@Resource(name = "feeDetailService")
	private IFeeDetailService feeDetailService;
	@Resource(name = "importFeeDetailHistory")
	private IImportFeeDetailHistory importFeeDetailHistory;
	@Resource(name = "propFeeCommService")
	private IPropFeeCommService propFeeCommService;
	@Resource(name = "propFeeDetailImportLogService")
	private IPropFeeDetailImportLogService propFeeDetailImportLogService;
	@Resource(name = "cerHouseholderService")
	private ICerHouseholderService cerHouseholderService;
	@Resource(name = "feeLogService")
	private IFeeLogService feeLogService;
	
	@Override
	public Response getAmonutByApartmentID(HttpServletRequest request,
			String commID, String apartmentID) throws Exception,
			AppBizException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Response importFeeDetail(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, Attachment attachments,
			String commID, String ispre) throws Exception {
		int version2003 = 2003;

		int version2007 = 2007;
		System.out.println(commID + "*************");
		int version = version2003;

		Workbook wb = null;

		Sheet sheet = null;
		String fileName = "";
		String excelFilePath = "";

		if (attachments == null) {

			throw new AppBizException(100002, "请选择要上传的文件");
		}

		DataHandler item = attachments.getDataHandler();
		fileName = item.getName();

		String temp = null;

		System.out.println(item.getContentType());

		if (fileName.endsWith(".xls")) {
			temp = fileName.replace(".xls", "");
			version = version2003;
		}

		else if (fileName.endsWith(".xlsx")) {
			version = version2007;
			temp = fileName.replace(".xlsx", "");
		}

		else {

			throw new AppBizException(100002, "文件格式错误");
		}

		if (!Pattern.matches("^[\\d]{4}([1][0-2]|[0][1-9])$", temp)) {

			throw new AppBizException(100002, "文件名格式错误");

		}

		String feeDate = temp.substring(0, 4) + "-" + temp.substring(4);

		InputStream stream = item.getInputStream();

		if (version == version2003) {

			wb = (Workbook) new HSSFWorkbook(stream);

		} else if (version == version2007) {

			wb = (Workbook) new XSSFWorkbook(stream);

		}

		sheet = wb.getSheetAt(0);
		int rowCount = sheet.getPhysicalNumberOfRows();// 获得总行数
		if (rowCount < 1) {
			throw new Exception("sheet页无数据");
		}

		// 获取小区的收费项目
		List<Map<String, Object>> types = propFeeTypeService
				.getPropFeeType(commID);

		if (types == null || types.size() == 0) {

			return this.abnormalResp(1000002, "请先配置缴费项目！");
		}

		Map<String, String> typeMap = new HashMap<String, String>();
		for (Map<String, Object> map : types) {

			typeMap.put(StringUtils.toString(map.get("feeTypeName")),
					StringUtils.toString(map.get("feeTypeID")));

		}

		// 解析excel

		Row row = sheet.getRow(0);
		short n = row.getLastCellNum();

		System.out.println(n + "*********************");

		// 获取excel的缴费项

		Map<String, Integer> eType = new HashMap<String, Integer>();
		int sindex = -1;
		for (int i = 0; i < n; i++) {

			String typeItem = this.getCellValue(row.getCell(i), null);

			int index = typeItem.indexOf("MX_");
			if (index != -1 && index == 0) {

				System.out.println(index);
				if (typeMap.get(typeItem.substring(index + 3)) != null) {
					eType.put(typeItem.substring(index + 3), i);
				}

			} else {

				if ("房屋管理号".equals(typeItem)) {

					sindex = i;

				}

			}

		}
		if (sindex == -1) {
			return this.abnormalResp(1000002, "缺少房屋管理号！");
		}

		// 0860dd08-d53f-47f4-aab6-0b17ebdfa52f
		System.out.println(typeMap);
		System.out.println(eType);
		// 解析excel
		Row row2 = null;

		List<Map<String, Object>> feeDetails = new ArrayList<Map<String, Object>>();
		Map<String, Object> temp1 = null;

		String pre = "1";
		String status = "0";
		if ("2".equals(ispre)) {

			status = "1";
			pre = "2";
		}
		if ("3".equals(ispre)) {

			status = "0";
			pre = "2";
		}

		for (int j = 1; j < rowCount; j++) {
			row2 = sheet.getRow(j);

			for (String key : eType.keySet()) {

				String val = this.getCellValue(row2.getCell(eType.get(key)),
						"0.##");
				if (StringUtils.isDouble(val)) {

					temp1 = new HashMap<String, Object>();
					temp1.put("feeTypeID", typeMap.get(key));
					temp1.put("amount", val);
					temp1.put("realamount", val);
					temp1.put("feeDate", feeDate);
					temp1.put("status", status);
					temp1.put("type", pre);
					temp1.put("ispre", pre);
					temp1.put("commID", commID);
					String sourceID = this.getCellValue(row2.getCell(sindex),
							null);

					temp1.put("sourceID", sourceID);

					if (!StringUtils.isBlank(sourceID)
							&& new BigDecimal(val).compareTo(BigDecimal.ZERO) > 0) {

						feeDetails.add(temp1);

					}

				}

			}

			// System.out.println(this.getCellValue(row2, "0.##"));

		}

		feeDetailService.bauthInsertFeeDetail(feeDetails);
		// new Thread(new ImportExcellRunnable(sheet, fileName,
		// importExcellBy0PoiService)).start();

		// }

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	private String getCellValue(Cell cell, String format1) throws Exception {
		String cellValue = null;
		try {
			if (cell != null) {
				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_NUMERIC: {
					if (DateUtil.isCellDateFormatted(cell)) {
						Date date = cell.getDateCellValue();
						SimpleDateFormat format = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						cellValue = format.format(date);

					} else {
						DecimalFormat df = new DecimalFormat(
								format1 == null ? "#" : format1);
						cellValue = df.format(cell.getNumericCellValue());
						// cellValue = String.valueOf((int) cell
						// .getNumericCellValue());
					}
				}
					break;
				case Cell.CELL_TYPE_STRING: {
					cellValue = cell.getStringCellValue().trim();
				}
					break;

				default:
					break;
				}
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
		return cellValue;
	}

	@Override
	public Response downFeeDetailHistory(HttpServletRequest servletRequest,
			final HttpServletResponse servletResponse, String search,
			String commID, final String comm) throws Exception {

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲小区信息");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);
		map.put("isShow", "1");

		/************************************************
		 * 返回结果设定
		 ************************************************/

		final PropFeeCommDto propFeeComm = propFeeCommService
				.findPropFeeCommByID(commID);
		String info = "房屋管理号,楼栋,房号,单元,";
		StringBuffer buffer = new StringBuffer();
		buffer.append(info);

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		final String filename = df.format(new Date());
		StreamingOutput stream = null;
		List<Map<String, Object>> propFees = PropertyUtils
				.turnToEntity(propFeeTypeService.bauthfindPropFeeTypeByMap(map));

		if (propFees == null || propFees.size() <= 0) {
			throw new AppBizException(2, "亲,该小区未配置相关的收费类目");
		}
		for (Map<String, Object> propFeeTypes : propFees) {
			buffer.append("MX_" + propFeeTypes.get("feeTypeName").toString()
					+ ",");

		}
		buffer.append("是否预缴,缴费日期");
		final String infos[] = buffer.toString().split(",");
		stream = new StreamingOutput() {
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				try {
					servletResponse.setContentType("application/vnd.ms-excel");
					servletResponse.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String((propFeeComm.getComm()
											+ "缴费历史记录表" + filename + ".xls")
											.getBytes("UTF-8"), "iso8859-1"));
					servletResponse.setHeader("Pragma", "No-cache");
					servletResponse.setHeader("Cache-Control", "No-cache");
					servletResponse.setDateHeader("Expires", 0); // 这个地方一定要进行编码的转换要不然中文字符会出现乱码.
					// 设置下载头信息.end,
					// SimpleDateFormat df = new
					// SimpleDateFormat("yyyy-MM-dd");

					InputStream fis = null;
					// PrintWriter out = response.getWriter();
					try {
						output = servletResponse.getOutputStream();
						jxl.write.WritableWorkbook wwb = jxl.Workbook
								.createWorkbook(output);

						jxl.write.WritableFont wfont = new jxl.write.WritableFont(
								WritableFont.createFont("宋体"), 12);
						WritableCellFormat font = new WritableCellFormat(
								NumberFormats.TEXT);
						font.setFont(wfont);
						font.setAlignment(jxl.format.Alignment.CENTRE);
						font.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						// 水平居中对齐

						// 竖直方向居中对齐
						jxl.write.WritableSheet ws = wwb.createSheet("Sheet1",
								1); // 设置标题.ws.addCell(new
						for (int l = 0; l < infos.length; l++) {
							ws.addCell(new Label(l, 0, infos[l], font));

							if (l == 0) {

								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）

								ws.setColumnView(l, cv);
							} else {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							}
						}

						wwb.write();
						if (wwb != null) {
							wwb.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {// 正常关闭输入输出流.
						if (fis != null) {
							fis.close();
						}
						if (output != null) {
							output.flush();
							output.close();
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new WebApplicationException(e);

				}
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@Override
	public Response ImportFeeDetailHistory(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, String commID,
			String importType, List<Attachment> attachments) throws Exception {
		String fileName = "";
		if (attachments == null || attachments.size() == 0) {
			throw new AppBizException(100002, "请选择要上传的文件");
		}

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲，小区信息");
		}

		Sheet sheet = null;

		for (Attachment attachment : attachments) {

			DataHandler item = attachment.getDataHandler();
			fileName = item.getName();

			InputStream inputStream = item.getInputStream();
			fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");

			org.apache.poi.ss.usermodel.Workbook book = null;

			if (fileName.endsWith(".xls")) {
				book = new HSSFWorkbook(inputStream);
			} else if (fileName.endsWith(".xlsx")) {
				book = new XSSFWorkbook(inputStream);
			} else {
				throw new AppBizException(100002, "文件格式错误");
			}
			sheet = book.getSheetAt(0);// 第一个工作表

			if (!ImportFeeDetailHistoryImpl.setFeeStatusLock(commID)) {

				throw new AppBizException(100002, "有账单在导入中，请稍后再试");

			}

			try {

				importFeeDetailHistory.importFeeDetailHistory(commID, sheet,
						fileName, "1");
			} catch (Exception e) {

				ImportFeeDetailHistoryImpl.setFeeStatusUnlock(commID);

			}

		}

		return this.normalResp();

	}

	@Override
	public Response getAllPropFeeDetail(HttpServletRequest servletRequest,
			String commID, String feeDate, String feeTypeID, String status,
			String search, String tsCreate, String pageIndex, String pageSize)
			throws Exception {
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = feeDetailService
				.findPropFeeDetailByPage(commID, feeDate, feeTypeID, status,
						tsCreate == null ? null : tsCreate,
						search == null ? null : search, pageUtils
								.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response ImportFeeHistory(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, String commID,
			String importType, List<Attachment> attachments) throws Exception {
		String fileName = "";
		if (attachments == null || attachments.size() == 0) {
			throw new AppBizException(100002, "请选择要上传的文件");
		}

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲，小区信息");
		}

		Sheet sheet = null;
		for (Attachment attachment : attachments) {

			DataHandler item = attachment.getDataHandler();
			fileName = item.getName();
			InputStream inputStream = item.getInputStream();
			fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");

			org.apache.poi.ss.usermodel.Workbook book = null;

			if (fileName.endsWith(".xls")) {
				book = new HSSFWorkbook(inputStream);
			} else if (fileName.endsWith(".xlsx")) {
				book = new XSSFWorkbook(inputStream);
			} else {
				throw new AppBizException(100002, "文件格式错误");
			}
			sheet = book.getSheetAt(0);// 第一个工作表

			if (!ImportFeeDetailHistoryImpl.setFeeStatusLock(commID)) {

				throw new AppBizException(100002, "有账单在导入中，请稍后再试");

			}
			try {

				importFeeDetailHistory.importFeeHistory(commID, sheet,
						fileName, "2");

			} catch (Exception e) {

				ImportFeeDetailHistoryImpl.setFeeStatusUnlock(commID);

			}

		}

		return this.normalResp();

	}

	@Override
	public Response editPropFeeDetail(HttpServletRequest servletRequest,
			PropFeeDetailDto propFeeDetail) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(propFeeDetail.getFeeDetailID(),
				"feeDetailID");
		if (error != null) {
			return error;
		}

		/************************************************
		 * 输入参数检查
		 ************************************************/
		// TODO;

		int result = feeDetailService.editPropFeeDetail(propFeeDetail);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}


		feeLogService.addLog(propFeeDetail.getCommID(),PropFeeLogDto.TYPE_FEEDETAIL, PropFeeLogDto.OP_FEEDETAIL_UPDATE,pageUtils.getBaseSession().getUserID() ,
        "修改导入的缴费信息"
				,propFeeDetail.getFeeDetailID(),JSON.toJSONString(propFeeDetail));
		
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改实体成功");

		return this.normalResp();
	}

	@Override
	public Response deletePropFeeDetail(HttpServletRequest servletRequest,
			String feeDetailID, String commID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(feeDetailID, "feeDetailID");
		if (error != null) {
			return error;
		}
		int result = feeDetailService.deletePropFeeDetailByLogic(feeDetailID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		
		feeLogService.addLog(commID,PropFeeLogDto.TYPE_FEEDETAIL, PropFeeLogDto.OP_FEEDETAIL_DEL,pageUtils.getBaseSession().getUserID() ,"删除缴费细项id为："+feeDetailID,feeDetailID);
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

	@Override
	public Response findPropFeeDetailByID(HttpServletRequest servletRequest,
			String feeDetailID) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(feeDetailID, "feeDetailID");
		if (error != null) {
			return error;
		}
		PropFeeDetailDto propFeeDetail = feeDetailService
				.findPropFeeDetailByID(feeDetailID);

		Map<String, Object> maps = new HashMap<String, Object>();

		if (propFeeDetail != null) {

		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "查询实体成功");
		return this.normalResp(propFeeDetail);
	}

	@Override
	public Response bauthdeleteFeeDetail(HttpServletRequest servletRequest,
			Map<String, Object> propFeeDetail) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		
		if (!propFeeDetail.containsKey("feeDetailIDs")) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "亲，缴费细项");
		}
		List<String> feeDetailIDs = (List<String>) propFeeDetail.get("feeDetailIDs");
		
		
	
		int result = feeDetailService.bauthdeleteFeeDetail(propFeeDetail);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		feeLogService.addLog(StringUtils.toString(propFeeDetail.get("commID")) ,PropFeeLogDto.TYPE_FEEDETAIL, PropFeeLogDto.OP_FEEDETAIL_DEL,pageUtils.getBaseSession().getUserID() ,"批量删除缴费细项",propFeeDetail.get("feeDetailIDs").toString(),"批量删除缴费细项 id为："+propFeeDetail.get("feeDetailIDs").toString());

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功("
				+ net.sf.json.JSONObject.fromObject(propFeeDetail).toString()
				+ ")");
		return this.normalResp(propFeeDetail);
	}

	@Override
	public Response deleteFeeDetail(HttpServletRequest servletRequest,
			Map<String, Object> propFeeDetail) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		int result = feeDetailService.deleteFeeDetail(propFeeDetail);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		feeLogService.addLog(propFeeDetail.get("commID").toString(),PropFeeLogDto.TYPE_FEEDETAIL, PropFeeLogDto.OP_FEEDETAIL_DEL,pageUtils.getBaseSession().getUserID() ,"按日期删除缴费细项："+propFeeDetail.get("feeDate")+"",JSON.toJSONString(propFeeDetail));

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功("
				+ net.sf.json.JSONObject.fromObject(propFeeDetail).toString()
				+ ")");
		return this.normalResp(propFeeDetail);
	}

	@Override
	public Response getLogInfos(HttpServletRequest servletRequest,
			String commID, String search, String pageIndex, String pageSize)
			throws Exception {
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeDetailImportLogService
				.findPropFeeDetailImportLogByPage(commID, null, search,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response ImportFeeHistory(Map<String, Object> map) throws Exception {

		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			map.put("pageEntity", PropertyUtils.turnToEntity(feeDetailService
					.findFeeDetailInfo(map)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthFindPropFeeDetails(HttpServletRequest servletRequest,
			Map<String, Object> propFeeDetail) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeDetail == null || propFeeDetail.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils.turnToEntity(feeDetailService
					.bauthfindPropFeeDetailByMap(propFeeDetail)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthSearchPropFeeDetails(
			HttpServletRequest servletRequest, Map<String, Object> propFeeDetail)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeDetail == null || propFeeDetail.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils.turnToEntity(feeDetailService
					.bauthSearchPropFeeDetails(propFeeDetail)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response getFeeDetails(HttpServletRequest servletRequest,
			Map<String, Object> propFeeDetail) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeDetail == null || propFeeDetail.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils.turnToEntity(feeDetailService
					.getFeeDetails(propFeeDetail)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();
	}

	@Override
	public Response changefeeDetailType(HttpServletRequest servletRequest,
			ChangeFeeTypeDto changeDto) throws Exception {
		
		if(StringUtils.isBlank(changeDto.getOldFeeTypeID())){
			
			return this.abnormalResp(-1, "旧类目不能为空");
		}
	    if(StringUtils.isBlank(changeDto.getNewFeeTypeID())){
			
			return this.abnormalResp(-1, "新类目不能为空");
		}
	    
          if(changeDto.getApartmentIDs()==null||changeDto.getApartmentIDs().size()==0){
			
			return this.abnormalResp(-1, "变更的房屋信息不能为空");
		}
		feeDetailService.changefeeDetailType(changeDto);
		
		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response monFeeList(HttpServletRequest servletRequest,
			String commID, String apartmentID,String pageIndex, String pageSize) throws Exception {
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,pageIndex,pageSize);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
//		 pageUtils.getBaseSession().getLoginName()
		List<CerHouseholderDto> c=	cerHouseholderService.findCerHouseholderByRelevantID(null, apartmentID, null, null, null,pageUtils.getBaseSession().getLoginName(), null);
		
		if(c==null||c.size()<=0){
			
			
			return this.abnormalResp(2, "非认证用户");
		}
		Map<String,Object>param=new HashMap<String,Object>();
		param.put("apartmentID", apartmentID);
		param.put("commID", commID);

		List<Map<String,Object>> list=	feeDetailService.monFeeList(param, pageUtils.getiPageIndex(), pageUtils.getiPageSize());
		Long total = ((Page<Map<String,Object>>) list).getTotal();


		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response monDetail(HttpServletRequest servletRequest, String commID,
			String feeDate, String apartmentID) throws Exception {
		Map<String,Object>param=new HashMap<String,Object>();
		param.put("apartmentID", apartmentID);
		param.put("commID", commID);
		param.put("feeDate", feeDate);
		// TODO Auto-generated method stub
		List<Map<String,Object>> list=	feeDetailService.monDetail(param);
		
		return this.normalResp(0,
				0, 0l,PropertyUtils.turnToEntity(list));
	}
	@Override
	public Response getMoreFeeDetail(HttpServletRequest servletRequest,
			Map<String, Object> params) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		int pageIndex=0;
		int pageSize=10;
		if(!StringUtils.isBlank(StringUtils.toString(params.get("ispage")))){
		
			params.put("pageIndex", StringUtils.toString(params.get("pageIndex"), "1"));
			params.put("pageSize", StringUtils.toString(params.get("pageSize"), "10"));
			pageIndex=Integer.parseInt(params.get("pageIndex").toString());
			pageSize=Integer.parseInt(params.get("pageSize").toString());
	
		}
		
		List<Map<String, Object>> list= feeDetailService.findMoreFeeDetailInfo(params);
		
		long total=0l;
		if(!StringUtils.isBlank(StringUtils.toString(params.get("ispage")))){
			
			total=((Page)list).getTotal();
		}
		
		// TODO Auto-generated method stub
		return this.normalResp(pageIndex, pageSize, total,PropertyUtils.turnToEntity(list) );
	}

	@Override
	public Response errEdit(HttpServletRequest servletRequest,
			PropFeeDetailDto propFeeDetail) throws Exception {
		
			/************************************************
			 * 检查session
			 ************************************************/
			PageUtils pageUtils = this.validateLogin(servletRequest);

			if (pageUtils.getResponse() != null) {
				return pageUtils.getResponse();
			}
			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			Response error = this.validateUUId(propFeeDetail.getFeeDetailID(),
					"feeDetailID");
			if (error != null) {
				return error;
			}

			/************************************************
			 * 输入参数检查
			 ************************************************/
			// TODO;
			PropFeeDetailDto oldp=	feeDetailService.findPropFeeDetailByID(propFeeDetail.getFeeDetailID());
			if(propFeeDetail.getAmount().compareTo(BigDecimal.ZERO)<=0){
				return this.abnormalResp(-1,
						"缴费金额不能为0");
				
			}
			
			if("1".equals(oldp.getStatus())){
				return this.abnormalResp(-1,
						"不能修改已缴缴费细项");
			}
			if(oldp.getAmount().compareTo(propFeeDetail.getAmount())==0){
				return this.normalResp();
				
			}
		
			int result = feeDetailService.editPropFeeDetail(propFeeDetail);
			
			
			if (!(result > 0)) {
				return this.abnormalResp(CodeConst.BIS_CODE_13006,
						InfoConst.BIS_INFO_13006);
			}
			
		
			feeLogService.addLog(propFeeDetail.getCommID(),PropFeeLogDto.TYPE_FEEDETAIL, PropFeeLogDto.OP_FEEDETAIL_UPDATE,pageUtils.getBaseSession().getUserID() ,
PropFeeLogDto.editStr("缴费金额", oldp.getAmount().toString(), propFeeDetail.getAmount().toString())
					,propFeeDetail.getFeeDetailID());

			
			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
					+ "时" + "修改实体成功");

			return this.normalResp();
		}

	@Override
	public Response errDel(HttpServletRequest servletRequest,
			String feeDetailID, String commID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(feeDetailID, "feeDetailID");
		if (error != null) {
			return error;
		}
		PropFeeDetailDto oldp=	feeDetailService.findPropFeeDetailByID(feeDetailID);
	
		
		if("1".equals(oldp.getStatus())){
			return this.abnormalResp(-1,
					"不能删除已缴缴费细项");
		}
		
		int result = feeDetailService.deletePropFeeDetailByLogic(feeDetailID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		
		feeLogService.addLog(commID,PropFeeLogDto.TYPE_FEEDETAIL, PropFeeLogDto.OP_FEEDETAIL_DEL,pageUtils.getBaseSession().getUserID() ,"删除缴费细项id为："+feeDetailID,feeDetailID);
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

}
